/**
 * Created by zhangqingxi on 2017-04-06.
 */
var modelPath = ROOT_PATH + '/emergency/rehearsalPlan/';


//初始化部门
function initDept(id) {

    $(id).combotree({
        url: ROOT_PATH + '/permission/department/getDepartmentTree.shtml?parentId=0',
        required: true,
        editable: false,
        prompt: '请选择'
    });

}
function initCombobx(id, url) {
    $(id).combobox({
        url: url,
        prompt: '请选择',
        required: true,
        editable: false,
        valueField: 'id',
        textField: 'text'
    });
}
//初始化组织人
function initUser() {
    $("#userName").textbox({
        iconWidth: 22,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                add_userInfo_func();
            }
        }, {
            iconCls: 'icon-remove',
            handler: function (e) {
                $(e.data.target).textbox('clear');
                $('#userId').val('');

            }
        }]
    });
}
function add_userInfo_func() {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack: function (data) {//窗口关闭后的回调函数
            var id = data[0].id;
            var name = data[0].realName;

            $('#userId').val(id);
            $('#userName').textbox('setValue', name);

        }
    });

};

//初始化 计划类型
function initRehearsalPlanType(id) {
    initCombobx(id, dictionaryByCode + rehearsalPlanType);
}
//初始化 演练级别
function initRehearsalLevel(id) {
    initCombobx(id, dictionaryByCode + rehearsalLevel);
}
//初始化 演练类型
function initRehearsalType(id) {
    initCombobx(id, dictionaryByCode + rehearsalType);
}
//初始化 演练类型
function initRehearsalModel(id) {
    initCombobx(id, dictionaryByCode + rehearsalModel);
}

//演练计划组织单位选中事件
function deptChange() {

    handleChange('#deptId', '#i_deptId', 'combotree');
}
//演练名称
function emergencyPlanChange() {
    handleChange('#emergencyPlanId', '#i_emergencyPlanId', 'combogrid');
}
//演练级别
function rehearsalLevelChange() {
    handleChange('#rehearsalLevelId', '#i_rehearsalLevelId');
}
//演练级别
function rehearsalTypeChange() {
    handleChange('#rehearsalTypeId', '#i_rehearsalTypeId');
}
//演练方式
function rehearsalModelChange() {
    handleChange('#rehearsalModelId', '#i_rehearsalModelId');
}


//预案
function initEmergencyPlan(id) {

    $(id).combogrid({
        required: true,
        editable: false,
        readonly: false,
        panelWidth: 900,
        prompt: '请选择',
        idField: 'id',
        textField: 'name',
        queryParams: {
            sort: 'd.addTime',
            order: 'desc'
        },
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        sortOrder: true,
        striped: true,
        url: findPlan,
        columns: [[
            {field: 'name', title: '预案名称', width: 10},
            {field: 'deptName', title: '所属单位', width: 10},
            {field: 'definitionName', title: '预案定义', width: 10},
            {field: 'hierarchyName', title: '预案层级', width: 10},
            {field: 'classificationName', title: '预案分类', width: 10},
            {field: 'typeName', title: '预案类型', width: 10},
            {field: 'deviceName', title: '装置场所', width: 10},
            {field: 'releaseDate', title: '发布时间', width: 10}
        ]]
    });
}
/**
 * 初始化参演人员表格
 */
function initUserTable() {
    var url = '';
    var rehearsalPlanId = $('#planId').val();
    if (rehearsalPlanId !== undefined) {
        url = findUserByRehearsalPlanId + rehearsalPlanId;
    }
    $('#user_table').datagrid({
        url: url,
        fitColumns: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: true,
        columns: [[
            {field: 'userId', width: 10, checkbox: true},
            {field: 'userName', title: '参演人员', width: 10},
            {field: 'deptName', title: '参演单位', width: 10}

        ]],
        toolbar: '#userToolbar'

    });
}
//添加参演人员
function initUserAddButton() {
    $('#btn_user_add').on('click', function () {
        WindowManager.openLayer({
            type: 2,
            title: '选择人员信息',
            area: ['1150px', '70%'],
            content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=1',
            callBack: function (data) {//窗口关闭后的回调函数

                for (var i = 0; i < data.length; i++) {
                    var userId = data[i].id;
                    var userName = data[i].realName;
                    var userDepartmentList = data[i].userDepartmentList;
                    var deptName = [];
                    for (var j = 0; j < userDepartmentList.length; j++) {
                        deptName.push(userDepartmentList[j].deptName);

                    }
                    addUserInfoToUserTable(userId, userName, deptName.join())
                }
            }
        });
    });
}
//userTable 删除
function initUserRemoveButton() {
    $('#btn_user_remove').on('click', function () {
        var $userTable = $('#user_table');
        //getSelections
        var rowData = $userTable.datagrid('getSelections');
        for (var i = 0; i < rowData.length; i++) {
            var index = $userTable.datagrid('getRowIndex', rowData[i]);
            $userTable.datagrid('deleteRow', index);
        }
    });
}
//添加数据到表格
function addUserInfoToUserTable(userId, userName, deptName) {
    var $userTable = $('#user_table');
    var rowData = $userTable.datagrid('getRows');
    for (var i = 0; i < rowData.length; i++) {
        var index = $userTable.datagrid('getRowIndex', rowData[i]);
        if (userId === rowData[i].userId) {
            $userTable.datagrid('deleteRow', index);
        }
    }
    $userTable.datagrid('insertRow', {
        index: 1,	// 索引从0开始
        row: {
            userId: userId,
            userName: userName,
            deptName: deptName
        }
    });

}
/**
 * 初始化问题表格
 */
function initProblemTable() {

    var rehearsalPlanId = $('#planId').val();

    var $table = $('#problem_table');
    $table.datagrid({
        url: findTask,
        queryParams: {
            'taskId': rehearsalPlanId
        },
        fitColumns: true,
        rownumbers: true,
        singleSelect: true,
        sortOrder: true,
        striped: true,
        fit: true,
        columns: [[
            {field: 'ckId', width: 10, checkbox: true},
            {field: 'taskName', title: '问题名称', width: 120},
            {field: 'taskDescribe', title: '问题描述', width: 80},
            {field: 'receiveUserName', title: '接收人', width: 100},
            {field: 'jsDeptName', title: '接收单位', width: 100},
            {field: 'requireTime', title: '要求完成日期', width: 100},
            {field: 'acceptUserName', title: '验收人', width: 100},
            {field: 'ysDeptName', title: '验收单位', width: 100},
            {
                field: 'state', title: '状态', width: 100, formatter: function (value, row, index) {
                var val = '整改中';
                if (value === 0) {
                    val = '已整改';
                    if (row.isYs === 0) {
                        val = '已验收';
                    }
                }
                return val;
            }
            }

        ]],
        view: detailview,
        detailFormatter: function (rowIndex, rowData) {
            return template('detail', rowData);
        },
        onExpandRow: function (index, row) {

            var rows = $table.datagrid('getRows');
            for (var i = 0; i < rows.length; i++) {
                var rowIndex = $table.datagrid('getRowIndex', rows[i]);
                if (index !== rowIndex) {
                    $table.datagrid('collapseRow', rowIndex);
                }
            }
            setTimeout(function () {
                $table.datagrid('resize');
            }, 100);
        },
        onLoadSuccess: function () {
            $('.problem_detail .easyui-textbox').textbox({
                editable: false
            });
            $('.problem_detail .easyui-datebox').textbox({
                editable: false
            });
        },
        toolbar: '#problemToolbar'
    });
}

//添加参演人员
function initProblemAddButton() {
    $('#btn_problem_add').on('click', function () {
        var $table = $('#problem_table');
        var rows = $table.datagrid('getRows');
        if (rows.length > 0) {
            if (rows[0].taskName === '') {
                return
            }
        }
        $table.datagrid('insertRow', {
            index: 0,	// 索引从0开始
            row: {
                taskName: '',
                taskDescribe: '',
                receiveUserId: '',
                receiveUserName: '',
                jsDeptName: '',
                requireTime: '',
                acceptUserId: '',
                acceptUserName: '',
                ysDeptName: '',
                isWrite: 0,
                state: ''
            }
        });
        $table.datagrid('expandRow', 0);

        initEasyUiStyle();


    });
}
//删除问题
function initProblemRemoveButton() {
    $('#btn_problem_remove').on('click', function () {
        var $table = $('#problem_table');
        var checkedRows = $table.datagrid('getChecked');
        if (checkedRows.length === 0) {
            layer.alert("选择需要删除的行！");
            return
        }
        var state = checkedRows[0].state;
        if (state === 0) {
            layer.alert("当前问题已整改无法删除");
            return
        }
        var index = $table.datagrid('getRowIndex', checkedRows[0]);
        $table.datagrid('deleteRow', index);
    });
}

function infoOtherDisable(val) {
    var $infoOther = $('#info_other');
    if (val === 0) {
        $infoOther.form('disableValidation');
        $infoOther.form('clear');
    } else {
        $infoOther.form('enableValidation');
        //单位
        $('#i_deptId').combotree('setValue', $('#deptId').combotree('getValue'));
        //演练名称
        $('#i_emergencyPlanId').combogrid('setValue', $('#emergencyPlanId').combogrid('getValue'));
        //级别
        $('#i_rehearsalLevelId').combobox('setValue', $('#rehearsalLevelId').combobox('getValue'));
        //类型
        $('#i_rehearsalTypeId').combobox('setValue', $('#rehearsalTypeId').combobox('getValue'));
        //方式
        $('#i_rehearsalModelId').combobox('setValue', $('#rehearsalModelId').combobox('getValue'));
    }

    $infoOther.toggle();
}

function initEasyUiStyle() {

    $('.taskName').textbox({
        required: true
    });
    $('.taskDescribe').textbox({
        required: true
    });
    $('.jsDeptName').textbox({
        editable: false
    });
    $('.requireTime').datebox({
        required: true,
        editable: false
    });
    $('.ysDeptName').textbox({
        editable: false
    });

    $('.problem_detail .easyui-linkbutton').linkbutton({
        iconCls: 'fa fa-save fa-lg'
    });
    initReceiveUser();
    initAcceptUser();
}
function initReceiveUser() {
    $(".receiveUserName").textbox({
        iconWidth: 22,
        required: true,
        editable: false,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                add_receiveUser_func(e);
            }
        }, {
            iconCls: 'icon-remove',
            handler: function (e) {
                $(e.data.target).textbox('clear');
                var $row = $(e.data.target).parentsUntil('.problem_detail');
                $row.find('.receiveUserId').val('');
                $row.find('.jsDeptName').textbox('clear');

            }
        }]
    });

}
function add_receiveUser_func(e) {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack: function (data) {//窗口关闭后的回调函数
            var id = data[0].id;
            var name = data[0].realName;
            var userDepartmentList = data[0].userDepartmentList;
            var deptName = [];
            for (var j = 0; j < userDepartmentList.length; j++) {
                deptName.push(userDepartmentList[j].deptName);
            }
            $(e.data.target).textbox('setValue', name);
            var $row = $(e.data.target).parentsUntil('.problem_detail');
            $row.find('.receiveUserId').val(id);
            $row.find('.jsDeptName').textbox('setValue', deptName.join());

        }
    });
}
function initAcceptUser() {
    $(".acceptUserName").textbox({
        iconWidth: 22,
        required: true,
        editable: false,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                add_acceptUser_func(e);
            }
        }, {
            iconCls: 'icon-remove',
            handler: function (e) {
                $(e.data.target).textbox('clear');
                var $row = $(e.data.target).parentsUntil('.problem_detail');
                $row.find('.acceptUserId').val('');
                $row.find('.ysDeptName').textbox('clear');
            }
        }]
    });

}
function add_acceptUser_func(e) {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack: function (data) {//窗口关闭后的回调函数
            var id = data[0].id;
            var name = data[0].realName;
            var userDepartmentList = data[0].userDepartmentList;
            var deptName = [];
            for (var j = 0; j < userDepartmentList.length; j++) {
                deptName.push(userDepartmentList[j].deptName);
            }
            $(e.data.target).textbox('setValue', name);
            var $row = $(e.data.target).parentsUntil('.problem_detail');
            $row.find('.acceptUserId').val(id);
            $row.find('.ysDeptName').textbox('setValue', deptName.join());

        }
    });
}
//保存行数据
function saveRowData(thisObj) {
    var $table = $('#problem_table');
    var $row = $(thisObj).parent().parent().parent();

    if ($row.form('validate') === false) {
        layer.msg('请正确填写表单信息');
        return
    }

    var rowIndex = $row.parent().parent().parent().prev().attr('datagrid-row-index');

    var taskName = $row.find('.taskName').textbox('getValue');
    var taskDescribe = $row.find('.taskDescribe').textbox('getValue');
    var receiveUserId = $row.find('.receiveUserId').val();
    var receiveUserName = $row.find('.receiveUserName').textbox('getValue');
    var jsDeptName = $row.find('.jsDeptName').textbox('getValue');
    var requireTime = $row.find('.requireTime').datebox('getValue');
    var acceptUserId = $row.find('.acceptUserId').val();
    var acceptUserName = $row.find('.acceptUserName').textbox('getValue');
    var ysDeptName = $row.find('.ysDeptName').textbox('getValue');

    $table.datagrid('updateRow', {
        index: rowIndex,
        row: {
            taskName: taskName,
            taskDescribe: taskDescribe,
            receiveUserId: receiveUserId,
            receiveUserName: receiveUserName,
            jsDeptName: jsDeptName,
            requireTime: requireTime,
            acceptUserId: acceptUserId,
            acceptUserName: acceptUserName,
            ysDeptName: ysDeptName,
            isWrite: 1,
            state: 1
        }
    });

    $table.datagrid('collapseRow', rowIndex);

}